import random

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from .models import *


# Create your views here.
def jdg_j(request):
    cs = Category.objects.all()
    tags = Tag.objects.all()
    books = Book.objects.all()
    res = render(request, "main/jdg_j.html", context={"cs": cs, "tags": tags, "books": books, }, )
    return res


def jdg_d(request):
    res = render(request, "main/jdg_d.html", context={}, )
    return res


def jdg_g(request):
    res = render(request, "main/jdg_g.html", context={}, )
    return res


def detail(request, num):
    book = Book.objects.get(id=num)
    res = render(request, "main/detail.html", context={"book": book, })
    return res


def tag(request, num):
    tags = Tag.objects.all()
    c_tag = Tag.objects.get(id=num)
    res = render(request, "main/tag.html", context={"tags": tags, "c_tag": c_tag, })
    return res


def change_recommend(request):
    book = Book.objects.all()
    book = list(book)
    datas = random.sample(book, k=4)
    return JsonResponse({
        "code": 0,
        "msg": "更换成功",
        "data": [{
            "book_id": data.id,
            "book_title": data.title,
            "book_img": data.img.url if data.img else None,
        } for data in datas],
    })

